import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'
import { addMemberCart, getMemberCartList, delMemberCart, memberCartMerge } from '@/apis/cart'

export const useCartStore = defineStore(
  'cart',
  () => {
    const cartList = ref([])
    const userStore = useUserStore()

    /**
     * 新增购物车
     */
    const addCart = async (cart) => {
      //判断是否登录
      if ((isLogin())) {
        await addMemberCart(cart.skuId, cart.count)
        await getCartList()
        return
      }
      //加入本地购物车
      const has = cartList.value.find((item) => cart.skuId === item.skuId)
      if (has) {
        has.count += cart.count
      } else {
        cartList.value.push(cart)
      }
    }

    /**
    * 删除
    */
    const delCart = async (skuId) => {
      if (isLogin()) {
        await delMemberCart([skuId])
        await getCartList()
        return
      }
      const idx = cartList.value.findIndex((item) => item.skuId === skuId)
      if (idx !== -1) cartList.value.splice(idx, 1)
    }

    /**
   * 购物车列表
   */
    const getCartList = async () => {
      if (isLogin()) {
        const carts = await getMemberCartList()
        cartList.value = carts
      }
      return cartList;
    }

    /**
     * 清空购物车
     */
    const clearCart = () => {
      cartList.value = []
    }
    /**
     * 合并购物车
     */
    const mergeCart = async () => {
      const carts = getMergeCarts()
      if (carts.length > 0) {
        await memberCartMerge(carts)
      }
      await getCartList()
    }
    const getMergeCarts = () => {
      if (!cartList.value) {
        return []
      }
      const carts = cartList.value.map(item => {
        return {
          skuId: item.skuId,
          selected: false,
          count: item.count
        }
      })
      return carts;
    }
    const totalNum = computed(() => {
      return cartList.value.reduce((a, b) => a + b.count, 0)
    })
    const totalPrice = computed(() => {
      return cartList.value.reduce((a, b) => a + b.count * b.nowPrice, 0)
    })
    const isLogin = () => {
      return userStore.userInfo.token !== ''
    }

    return {
      cartList,
      addCart,
      delCart,
      totalNum,
      totalPrice,
      getCartList,
      clearCart,
      mergeCart
    }
  },
  {
    persist: {
      key: 'cartList',
      storage: sessionStorage,
      paths: ['cartList'],
    },
  },
)
